/*
 * @Author: mayijun
 * @Date: 2022-05-14 11:12:52
 * @LastEditors: mayijun
 * @LastEditTime: 2022-08-10 10:28:10
 */
//取数设置，分为自助取数和模板取数
import { defineComponent, onMounted, reactive, ref, toRaw, watch } from 'vue';
import './index.scss';
import { ElButton, ElDivider, ElMessage } from 'element-plus';
import DragTree from './components/dragTree/index';
import API from '@/services';
import ConditionTree from './components/conditionTree';
import TableHeaderDrag from './components/tableHeaderDrag';
import TaskSaveDrawer from './components/taskSaveDrawer';
import _ from 'lodash';
import { downLoadFile } from '@/utils/http';
import { useRoute, useRouter } from 'vue-router';
import * as RouteNames from '@/router/consts';
import { CaretBottom } from '@element-plus/icons-vue';
import shrinkLeft from '@/assets/images/shrinkLeft.svg';
import activeShrinkLeft from '@/assets/images/activeShrinLeft.svg';
import PageCaontainer from '@/arco-components/PageContainer';
import dragTop from '@/assets/images/dragTop.svg';
import { store } from '@/store';
import { bindType } from '@/hooks/base';

const FetchDataConfig = defineComponent({
  name: 'FetchDataConfig',
  setup: (props, { slots, attrs, emit }) => {
    const route = useRoute();
    const router = useRouter();
    /* 收缩状态 */
    const toggle = ref(false);
    const shrinkIcon = ref(shrinkLeft);

    /** 场景取数的相关参数 */
    const scenesList = ref<any>([]);
    const defaultSceneName = ref('');
    const defaultSceneId = ref(0);
    const isShowScenes = ref(false);

    let state = reactive({
      metricsTreeList: [] as any[], //指标树
      dimensionTreeList: [] as any[], //维度树
      treeNodeData: {
        childrenTree: null,
        opType: 'AND', // 与或非
        //可选指标或维度: 数值 ,检举；日期
        treeList: [] as any[], //节点数据
        level: 0
      } as any, //筛选条件数据
      tableHeaderList: [] as any[], //表头拖拽数据
      maxQueryNumber: 1000,
      visibleSave: false,
      saveLoading: false,
      editFormData: undefined as any,
      taskHisId: 0, //任务id
      tableData: {
        list: [] as any[],
        pageNum: 1,
        pageSize: 10,
        total: 0
      }, //表格数据
      previewData: {} as any, //预览数据
      command: '1',
      isHasTreeNode: false, //判断是否找到树节点
      chosenDimensionIds: [] as any[], //可选维度id
      chosenMetricsIds: [] as any[], //可选指标id
      isMetricsFavorite: false,
      metricsNodkey: '', //指标树展开
      dimensionNodkey: '', //维度树展开
      timePeriodNodkey: '' //统计粒度树展开
    });

    // 查询可选树结构
    const getIndexTree = async (
      isMetricsFavorite?: boolean,
      chosenDimensionIds?: any[],
      chosenMetricsIds?: any[],
      dimensionContent?: '',
      metricsContent?: ''
    ) => {
      const { code, data } = await API.taskManagerV1.getHintMetricsDimension({
        chosenDimensionIds,
        chosenMetricsIds,
        isMetricsFavorite,
        dimensionContent,
        metricsContent
      });
      if (code === 200 && data) {
        if (data.metrics) {
          //树形结构处理
          let metricsTreeList: any[] = [];
          let root: any = data.metrics[0];
          //处理树结构
          if (isMetricsFavorite) {
            getMetricsTreeData(metricsTreeList, root.isolateMetrics, true);
          } else {
            getMetricsTreeData(
              metricsTreeList,
              root.subject2MetricsTreeRoots,
              false
            );
          }
          state.metricsTreeList = metricsTreeList;
        }
        if (data.dimension) {
          //树形结构处理
          let dimensionTreeList: any[] = [];
          //处理维度
          let root: any = data.dimension[0];
          let dimensionRoot = {
            id: '',
            cnName: root.mark,
            num: root.dimNum,
            children: []
          };
          //处理树结构
          getDimensionTreeData(dimensionRoot, root.isolateDims);
          dimensionTreeList.push(dimensionRoot);
          //处理统计时间
          let rootTime: any = data.dimension[1];
          let timeRoot = {
            id: '',
            cnName: rootTime.mark,
            num: rootTime.dimNum,
            children: []
          };
          //处理树结构
          getDimensionTreeData(timeRoot, rootTime.isolateDims);
          dimensionTreeList.push(timeRoot);
          state.dimensionTreeList = dimensionTreeList;
        }
      }
    };

    //刷新可选树结构
    const refreshTree = (type: any, id: any) => {
      if (type == 1) {
        let obj = state.chosenMetricsIds.includes(id);
        if (!obj) {
          state.chosenMetricsIds.push(id);
        }
      } else {
        let obj = state.chosenDimensionIds.includes(id);
        if (!obj) {
          state.chosenDimensionIds.push(id);
        }
      }
    };

    //转换指标树结构
    const getMetricsTreeData = (
      metricsTreeList: any,
      children: any[],
      isMetricsFavorite: boolean
    ) => {
      if (children) {
        children.map((item) => {
          let treeNode: any = {};
          if (!item.cnName) {
            treeNode.id = item.subjectId;
            treeNode.cnName = item.subjectName;
            treeNode.num = item.metricsNum;
            treeNode.children = [];
          } else {
            treeNode = item;
          }
          if (metricsTreeList) {
            metricsTreeList.push(treeNode);
          }
          if (!isMetricsFavorite && item.children && item.children.length > 0) {
            getMetricsTreeData(
              treeNode.children,
              item.children,
              isMetricsFavorite
            );
          } else {
            getMetricsTreeData(
              treeNode.children,
              item.getNumMetrics,
              isMetricsFavorite
            );
          }
        });
      }
    };

    //转换维度树结构
    const getDimensionTreeData = (root: any, children: any[]) => {
      if (children) {
        children.map((item) => {
          let treeNode: any = {};
          if (item.subjectId) {
            treeNode.id = item.subjectId;
            treeNode.cnName = item.subjectName;
            treeNode.num = item.dimNum ? item.dimNum : '';
            treeNode.children = [];
          } else {
            treeNode = item;
          }
          root.children.push(treeNode);
          if (item.children && item.children.length > 0) {
            getDimensionTreeData(treeNode, item.children);
          }
          if (item.getNumDimension && item.getNumDimension.length > 0) {
            getDimensionTreeData(treeNode, item.getNumDimension);
          }
        });
      }
    };

    //删除表头对象
    const removeItem = (id: string, removeIndex: number) => {
      //找到被删除的对象
      let removeObj = state.tableHeaderList.find((item) => item.id == id);
      //找到筛选条件是否存在相同的id
      let isHasTree = findTreeSomeId(state.treeNodeData, id);
      //如果是维度直接删除
      if (removeObj.dimensionType) {
        //删除表头
        state.tableHeaderList.splice(removeIndex, 1);
        //删除可选维度id数组
        if (!isHasTree) {
          let idIndex = state.chosenDimensionIds.findIndex((obj) => obj == id);
          state.chosenDimensionIds.splice(idIndex, 1);
        }
      } else {
        //删除表头
        state.tableHeaderList.splice(removeIndex, 1);
        //删除后是否还能找到相同的指标
        let isHas = state.tableHeaderList.some((item) => item.id == id);
        //没有找到，删除可选指标id数组
        if (!isHas && !isHasTree) {
          let idIndex = state.chosenMetricsIds.findIndex((obj) => obj == id);
          state.chosenMetricsIds.splice(idIndex, 1);
        }
      }

      //清空表头对应列的数据
      if (state.tableData.list && state.tableData.list.length > 0) {
        state.tableData.list[removeIndex] = '';
      }
    };

    //查找树节点是否存在相同的id
    const findTreeSomeId: any = (treeNode: any, id: any) => {
      let obj = treeNode.treeList.find((item: any) => item.id == id);
      if (obj) {
        return true;
      } else {
        if (treeNode.childrenTree) {
          return findTreeSomeId(treeNode.childrenTree, id);
        }
        return false;
      }
    };

    //更新表头
    const updateItem = (item: any, index: any) => {
      let headerList = state.tableHeaderList;
      headerList[index] = item;
      state.tableHeaderList = headerList;
    };

    //过滤表头列
    const filterColomn = (item: any) => {
      let treeNode: any[] = [];
      //克隆一遍对象数组
      state.tableHeaderList.map((item: any, index: number) => {
        //设置每一项的索引
        item.sortIndex = index;
        item = _.cloneDeep(toRaw(item));
        treeNode.push(item);
      });

      //维度不能重复过滤
      let filterList = treeNode.filter(
        (obj) => obj.dimensionType && obj.id == item.id
      );
      //2项说明有重复的
      if (filterList.length == 2) {
        //获取这一项的索引
        let sortIndex = filterList[filterList.length - 1].sortIndex;
        //删除这个项
        let newList = treeNode.filter((obj) => obj.sortIndex != sortIndex);
        state.tableHeaderList = newList;
        ElMessage.warning('该数据项已经添加，请勿重复添加.');
      } else {
        state.tableHeaderList = treeNode;
      }
    };

    //筛选条件数据处理
    const conditionData = (
      condition: any,
      treeNodeData: any,
      chosenDimensionIds: any[],
      chosenMetricsIds: any[],
      chosenTimePeriodIds: any[]
    ) => {
      if (treeNodeData.treeList.length == 1 && !treeNodeData.childrenTree) {
        let treeNode = treeNodeData.treeList[0];
        console.log(treeNode.value, '节点数据');
        treeNode = _.cloneDeep(toRaw(treeNode));
        let valueArr: any[] = [];
        let contentArr: any[] = [];
        if (
          treeNode.columnType === bindType.DIMENSION ||
          (Array.isArray(treeNode.value) && treeNode.dimensionType)
        ) {
          treeNode.value?.forEach((item: any) => {
            if (item.value && item.label) {
              valueArr.push(item.value);
              contentArr.push(item.label);
            } else {
              valueArr = item.value;
              contentArr = item.value;
            }
          });
          treeNode.value = valueArr;
          treeNode.content = contentArr;
        } else {
          treeNode.content = treeNode.value;
        }

        //只有一条时的处理
        let nodeAsRoot: any = {
          id: treeNode.id,
          name: treeNode.cnName,
          dataType: treeNode.dataType,
          dataTypeId: treeNode.dataTypeId,
          operator: treeNode.operator,
          rangeType: treeNode.rangeType,
          type: treeNode.dimensionType ? 2 : 1,
          value: Array.isArray(treeNode.value)
            ? treeNode.value.join(',')
            : treeNode.value,
          content: Array.isArray(treeNode.content)
            ? treeNode.content.join(',')
            : treeNode.content
        };
        if (treeNode.dimensionType) {
          nodeAsRoot.dimensionType = treeNode.dimensionType;
        }
        condition.nodeAsRoot = nodeAsRoot;

        //判断维度还是指标
        if (treeNode.dimensionType) {
          //选择的维度id数组
          chosenDimensionIds.push(treeNode.id);
        } else {
          //选择的指标id数组
          chosenMetricsIds.push(treeNode.id);
        }
      } else {
        //多条处理
        let opAsRoot = {};
        conditionDataTree(
          opAsRoot,
          treeNodeData,
          chosenDimensionIds,
          chosenMetricsIds,
          chosenTimePeriodIds
        );
        condition.opAsRoot = opAsRoot;
      }
    };

    //筛选条件树数据处理
    const conditionDataTree = (
      ops: any,
      treeNodeData: any,
      chosenDimensionIds: any[],
      chosenMetricsIds: any[],
      chosenTimePeriodIds: any[]
    ) => {
      ops.nodes = {}; //map对象
      ops.opType = treeNodeData.opType;
      ops.ops = {};
      treeNodeData.treeList.map((item: any, index: number) => {
        console.log(item, '处理的是多条数据');
        item = _.cloneDeep(toRaw(item));
        let valueArr: any[] = [];
        let contentArr: any[] = [];
        if (
          item.columnType === bindType.DIMENSION ||
          (Array.isArray(item.value) && item.dimensionType)
        ) {
          item.value?.forEach((child: any) => {
            // 这里写是因为任务回显 和 手动选择所获取的值是不一样的
            if (child.value && child.label) {
              valueArr.push(child.value);
              contentArr.push(child.label);
            } else {
              valueArr = item.value;
              contentArr = item.value;
            }
          });
          item.value = valueArr;
          item.content = contentArr;
        } else {
          item.content = item.value;
        }

        let nodeAsRoot: any = {
          id: item.id,
          name: item.cnName,
          dataType: item.dataType,
          dataTypeId: item.dataTypeId,
          operator: item.operator,
          rangeType: item.rangeType,
          type: item.dimensionType ? 2 : 1,
          value: Array.isArray(item.value) ? item.value.join(',') : item.value,
          content: Array.isArray(item.content)
            ? item.content.join(',')
            : item.content
        };
        if (item.dimensionType) {
          nodeAsRoot.dimensionType = item.dimensionType;
        }
        ops.nodes[index] = nodeAsRoot;
        //判断维度还是指标
        if (item.dimensionType) {
          let dim = chosenDimensionIds.find((obj) => obj == item.id);
          if (!dim) {
            //选择的维度id数组
            chosenDimensionIds.push(item.id);
          }
        } else {
          let met = chosenMetricsIds.find((obj) => obj == item.id);
          if (!met) {
            //选择的指标id数组
            chosenMetricsIds.push(item.id);
          }
        }
      });

      //有子条件
      if (treeNodeData.childrenTree) {
        ops.ops[treeNodeData.level] = {};
        conditionDataTree(
          ops.ops[treeNodeData.level],
          treeNodeData.childrenTree,
          chosenDimensionIds,
          chosenMetricsIds,
          chosenTimePeriodIds
        );
      }
    };

    //表头数据处理
    const tableHeaderData = (previewData: any) => {
      previewData.view = {
        dimFields: {},
        metricsFields: {},
        metricsCombFields: {}
      };
      state.tableHeaderList.map((item: any, index: any) => {
        //选择的维度
        if (item.dimensionType) {
          let dimField = {
            dimensionType: item.dimensionType,
            dimensionTypeDesc: item.dimensionTypeDesc,
            id: item.id,
            enName: item.enName,
            cnName: item.cnName
          };
          previewData.view.dimFields[index] = dimField;
          let dim = previewData.chosenDimensionIds.find(
            (obj: any) => obj == item.id
          );

          if (!dim) {
            //选择的维度id数组
            previewData.chosenDimensionIds.push(item.id);
          }
        } else {
          //组合指标
          if (item.combinationName) {
            let metricsCombField = {
              combinationName: item.combinationName,
              calculationFormula: item.calculationFormula,
              arithmetics: [] as any[]
            };
            item.arithmeticList.map((obj: any) => {
              let arith = {
                afterSymbol: obj.afterSymbol,
                beforeSymbol: obj.beforeSymbol,
                numberInput: obj.numInput,
                metricsField: {
                  aggregation: obj.CombineEnumName,
                  aggregationId: obj.CombineEnumVal,
                  cnName: obj.selectIndexName,
                  dataType: obj.dataType,
                  dataTypeId: obj.dataTypeId,
                  enName: obj.enName,
                  id: obj.selectIndexId
                }
              };
              metricsCombField.arithmetics.push(arith);
              let met = previewData.chosenMetricsIds.find(
                (child: any) => child == obj.selectIndexId
              );
              if (!met) {
                //选择的指标id数组
                previewData.chosenMetricsIds.push(obj.selectIndexId);
              }
            });
            previewData.view.metricsCombFields[index] = metricsCombField;
          } else {
            let metricsField = {
              id: item.id,
              enName: item.enName,
              aggregationId: item.aggregationId,
              aggregation: item.aggregation,
              cnName: item.cnName,
              dataTypeId: item.dataTypeId
            };
            previewData.view.metricsFields[index] = metricsField;
            let met = previewData.chosenMetricsIds.find(
              (obj: any) => obj == item.id
            );
            if (!met) {
              //选择的指标id数组
              previewData.chosenMetricsIds.push(item.id);
            }
          }
        }
      });
    };

    // 处理预览数据
    const doPreviewData = () => {
      // 简单输入性校验
      if (!simpleValidate()) {
        return false;
      }
      //预览数据对象
      let previewData: any = {};
      //数据限制条数
      previewData.limit = state.maxQueryNumber;
      //场景id
      //previewData.sceneId
      //选择的维度id数组
      previewData.chosenDimensionIds = [];
      //选择的指标id数组
      previewData.chosenMetricsIds = [];
      // 选择统计粒度id数组
      previewData.chosenTimePeriodIds = [];
      //条件数据处理
      previewData.condition = {};
      conditionData(
        previewData.condition,
        state.treeNodeData,
        previewData.chosenDimensionIds,
        previewData.chosenMetricsIds,
        previewData.chosenTimePeriodIds
      );
      //表格数据处理
      tableHeaderData(previewData);
      if (isShowScenes.value) {
        let chosenTimePeriodIdsArr: any[] = [];
        let chosenDimensionIdsArr: any[] = [];
        previewData.chosenDimensionIds.forEach((item: any) => {
          if (item > 0) {
            chosenDimensionIdsArr.push(item);
          }
          if (item < 0) {
            chosenTimePeriodIdsArr.push(item);
          }
        });
        previewData.chosenDimensionIds = chosenDimensionIdsArr;
        previewData.chosenTimePeriodIds = chosenTimePeriodIdsArr;
      }
      return previewData;
    };

    //数据预览
    const doPreview = async () => {
      let previewData = doPreviewData();
      if (previewData) {
        state.saveLoading = true;
        const { code, data, msg }: any =
          await API.taskManagerV1.postPreviewData(previewData);
        if (code === 200 && data) {
          state.taskHisId = data;
          getResultList();
        } else {
          ElMessage.error(msg);
          state.saveLoading = false;
        }
      }
    };

    // 根据设置条件查看查询结果
    const getResultList = async () => {
      state.tableData.list = [];
      const postParam: any = {
        taskHisId: state.taskHisId,
        pageNum: state.tableData.pageNum,
        pageSize: state.tableData.pageSize,
        limit: state.maxQueryNumber
      };
      const { data, code }: any = await API.taskManagerV1.postListData(
        postParam
      );
      if (code === 200 && Array.isArray(data.list)) {
        state.tableData.list = data.list;
        console.log(state.tableData.list, '最后的列表')
        state.tableData.pageNum = data.pageNum == 0 ? 1 : data.pageNum;
        state.tableData.pageSize = data.pageSize == 0 ? 10 : data.pageSize;
        state.tableData.total = data.total;
      }
      state.saveLoading = false;
    };

    //分页查询
    const pageChange = (v: any) => {
      state.tableData.pageSize = v;
      getResultList();
    };
    //页数改变
    const currentChange = (v: any) => {
      state.tableData.pageNum = v;
      getResultList();
    };

    // 简单验证是否要预览或保存
    const simpleValidate = () => {
      if (state.tableHeaderList.length == 0) {
        ElMessage.warning('请选择取数结果列表项');
        return false;
      } else if (state.tableHeaderList.length > 0) {
        let newList = state.tableHeaderList.filter(
          (item) => !item.dimensionType
        );
        if (newList.length == 0) {
          ElMessage.warning('取数结果列表项至少选择一个指标');
          return false;
        }
      } else if (state.maxQueryNumber == 0) {
        ElMessage.warning('请选择查询条数');
        return false;
      }
      return true;
    };

    //保存任务
    const openSave = () => {
      if (!simpleValidate()) {
        return false;
      }
      state.visibleSave = true;
    };
    // 关闭保存侧边栏
    const drawerClose = () => {
      state.visibleSave = false;
    };
    //保存数据
    const saveTask = async (formData: any) => {
      //获取预处理数据
      let previewData = doPreviewData();

      state.saveLoading = true;
      //保存参数
      let params = {
        ...formData,
        getNumTaskConfig: previewData
      };
      if (isShowScenes.value) {
        params.getNumTaskConfig.sceneId = defaultSceneId.value;
      }
      if (route.query.taskId) {
        let { code, data }: any = isShowScenes.value
          ? await API.sceneTaskManager.postUpdateTask(params)
          : await API.taskManagerV1.postUpdateTask(params);
        if (code === 200) {
          ElMessage.success('保存成功');
          //跳转任务管理
          router.push({ name: RouteNames.ROUTE_APPLICATIONFETCHTASK });
        } else {
          // ElMessage.error();
        }
      } else {
        let { code, data }: any = isShowScenes.value
          ? await API.sceneTaskManager.postSaveTask(params)
          : await API.taskManagerV1.postSaveTask(params);
        if (code === 200) {
          ElMessage.success('保存成功');
          //跳转任务管理
          router.push({ name: RouteNames.ROUTE_APPLICATIONFETCHTASK });
        } else {
          // ElMessage.error();
        }
      }

      state.saveLoading = false;
      drawerClose();
    };

    // 更新树层级
    const listLevel = (node: any, level: number, isUp: boolean) => {
      node.level = level;
      node.treeList.map((item: any, index: any) => {
        item.level = node.level + '_' + index;
        //排序后重新赋值
        //returnNode(item, node);
      });
      if (node.childrenTree) {
        let num = 0;
        if (isUp) {
          num = level + 1;
        } else {
          num = level - 1;
        }
        listLevel(node.childrenTree, num, isUp);
      }
    };

    // 添加节点
    const addNode = (treeNodeData?: any) => {
      if (treeNodeData.opType) {
        if (treeNodeData.treeList?.length > 0) {
          let treeNode: any[] = [];
          //克隆一遍对象数组
          treeNodeData.treeList.map((item: any, index: number) => {
            item = _.cloneDeep(toRaw(item));
            treeNode.push(item);
          });
          treeNodeData.treeList = treeNode;

          listLevel(treeNodeData, treeNodeData.level, true);
        }
      } else {
        //表示当前层级没有拖拽数据，不能创建下一层
        if (state.treeNodeData.treeList.length == 0) {
          ElMessage.warning('请先添加当前层级的条件');
          return false;
        }
        //在最外层添加一层节点
        let treeNodeData: any = {
          childrenTree: state.treeNodeData,
          opType: 'AND', // 与或非
          //可选指标或维度: 数值 ,检举；日期
          treeList: [] as any[], //节点数据
          level: 0
        };
        listLevel(treeNodeData, 0, true);
        state.treeNodeData = treeNodeData;
      }
    };

    // 删除节点
    const removeNode = (node: any, parentNode: any) => {
      parentNode.treeList = parentNode.treeList.filter((item: any) => {
        if (node.level != item.level) {
          return true;
        } else {
          //判断表头是否存在
          let tableHeader = state.tableHeaderList.find(
            (item) => item.id == item.id
          );
          //不存在进行删除
          if (!tableHeader) {
            //删除树结构筛选
            if (item.dimensionType) {
              let idIndex = state.chosenDimensionIds.findIndex(
                (obj) => obj == item.id
              );
              state.chosenDimensionIds.splice(idIndex, 1);
            } else {
              let idIndex = state.chosenMetricsIds.findIndex(
                (obj) => obj == item.id
              );
              state.chosenMetricsIds.splice(idIndex, 1);
            }
          }
        }
      });
      //根节点无数据，并且有子节点
      if (
        parentNode.level == 0 &&
        parentNode.treeList.length === 0 &&
        parentNode.childrenTree
      ) {
        state.treeNodeData = parentNode.childrenTree;
      }
      //根节点无数据，没有子节点
      else if (parentNode.level == 0 && !parentNode.childrenTree) {
        state.treeNodeData = parentNode;
      }
      //只有一条数据，并且没有子节点
      else if (
        parentNode.level != 0 &&
        parentNode.treeList.length === 1 &&
        !parentNode.childrenTree
      ) {
        let nodeData = parentNode.treeList[0];
        let pNode = getParentNodeByKey(
          parentNode.level,
          state.treeNodeData,
          null
        );
        pNode.childrenTree = null;
        pNode.treeList.push(nodeData);
      }
      // 没有数据，并且有子节点
      else if (
        parentNode.level != 0 &&
        parentNode.treeList.length === 0 &&
        parentNode.childrenTree
      ) {
        const children = parentNode.childrenTree;
        let pNode = getParentNodeByKey(
          parentNode.level,
          state.treeNodeData,
          null
        );
        pNode.childrenTree = children;
      }
      if (parentNode.level == 0) {
        listLevel(state.treeNodeData, 0, true);
      } else {
        listLevel(state.treeNodeData, state.treeNodeData.level, true);
      }
    };

    //查找父节点
    const getParentNodeByKey = (
      level: string,
      treeNode: any,
      parentNode: any
    ) => {
      let pNode: any;
      if (treeNode.level === level) {
        pNode = parentNode;
        return pNode;
      }
      if (treeNode.childrenTree) {
        pNode = getParentNodeByKey(level, treeNode.childrenTree, treeNode);
      }
      return pNode;
    };

    // 下载
    const downloadTask = async () => {
      if (state.taskHisId == 0) {
        ElMessage.warning('暂无数据');
        return false;
      }
      await downLoadFile({
        url:
          '/task-manager-v1/task-his/data/download?hisIds=' + state.taskHisId,
        method: 'get'
      });
    };

    //查询任务详情
    const taskDetail = async (id: any) => {
      let { code, data }: any = await API.taskManagerV1.getTaskDetailById({
        id
      });
      if (code === 200 && data) {
        //配置详情
        if (data.detailJson) {
          let info = JSON.parse(data.detailJson);
          console.log(info, '此时的详情信息');

          if (isShowScenes.value && info.sceneId) {
            scenesList.value.forEach((item: any) => {
              if (item.id === info.sceneId) {
                handleSelectFromDetail(item);
                return;
              }
            });
          }
          setTimeout(() => {
            //保存参数
            state.editFormData = data;
            delete state.editFormData.detailJson;
            delete state.editFormData.cycleTypeDesc;
            //解析详情
            state.maxQueryNumber = info.limit; //查询条数
            //可选id列表
            state.chosenDimensionIds = info.chosenDimensionIds;
            state.chosenMetricsIds = info.chosenMetricsIds;
            //筛选条件
            state.isHasTreeNode = false;
            if (info.condition.nodeAsRoot) {
              let targetArray: any[] = [];
              //在可选树形里面查找对应的节点
              if (info.condition.nodeAsRoot.type == 1) {
                findTreeItem(
                  state.metricsTreeList,
                  targetArray,
                  info.condition.nodeAsRoot,
                  1
                );
              } else {
                findTreeItem(
                  state.dimensionTreeList,
                  targetArray,
                  info.condition.nodeAsRoot,
                  1
                );
              }
              state.treeNodeData.treeList = targetArray;
              listLevel(state.treeNodeData, state.treeNodeData.level, true);
            } else {
              let treeNodeData: any = {
                childrenTree: null,
                opType: 'AND', // 与或非
                //可选指标或维度: 数值 ,检举；日期
                treeList: [] as any[], //节点数据
                level: 0
              };
              findTreeItemOp(info.condition.opAsRoot, treeNodeData);
              state.treeNodeData = treeNodeData;
              listLevel(state.treeNodeData, state.treeNodeData.level, true);
            }

            //表头信息
            state.isHasTreeNode = false;
            let tableHeaderList: any[] = [];
            if (
              info.view.dimFields &&
              Object.keys(info.view.dimFields).length > 0
            ) {
              fintTable(
                state.dimensionTreeList,
                tableHeaderList,
                info.view.dimFields,
                2
              );
            }
            if (
              info.view.metricsFields &&
              Object.keys(info.view.metricsFields).length > 0
            ) {
              fintTable(
                state.metricsTreeList,
                tableHeaderList,
                info.view.metricsFields,
                2
              );
            }
            if (
              info.view.metricsCombFields &&
              Object.keys(info.view.metricsCombFields).length > 0
            ) {
              let source = info.view.metricsCombFields;
              for (let key in source) {
                let item: any = {};
                item.combinationName = source[key].combinationName;
                item.arithmeticList = [];
                source[key].arithmetics.map((obj: any) => {
                  let arith = {
                    numInput: obj.numberInput,
                    afterSymbol: obj.afterSymbol,
                    beforeSymbol: obj.beforeSymbol,
                    CombineEnumName: obj.metricsField.aggregation,
                    CombineEnumVal: obj.metricsField.aggregationId,
                    selectIndexName: obj.metricsField.cnName,
                    dataType: obj.metricsField.dataType,
                    dataTypeId: obj.metricsField.dataTypeId,
                    selectIndexId: obj.metricsField.id
                  };
                  item.arithmeticList.push(arith);
                });
                tableHeaderList.push(item);
              }
            }
            state.tableHeaderList = tableHeaderList;
            console.log(state.tableHeaderList, '最终表头数据');
            console.log(state.treeNodeData, '最终筛选条件数据');
          }, 500);
        } else {
          ElMessage.warning('数据不完整，无法编辑');
        }
      }
    };

    //树形筛选条件处理
    const findTreeItemOp = (treeNode: any, treeNodeData: any) => {
      let targetArray: any[] = [];
      for (let key in treeNode.nodes) {
        state.isHasTreeNode = false;
        let source = treeNode.nodes[key];
        if (source.type == 1) {
          findTreeItem(state.metricsTreeList, targetArray, source, 1, key);
        } else {
          findTreeItem(state.dimensionTreeList, targetArray, source, 1, key);
        }
      }
      treeNodeData.treeList = targetArray;
      if (treeNode.opType) {
        treeNodeData.opType = treeNode.opType;
        for (let key in treeNode.ops) {
          treeNodeData.childrenTree = {};
          findTreeItemOp(treeNode.ops[key], treeNodeData.childrenTree);
        }
      }
    };

    //表头数据整理
    const fintTable = (
      treeArray: any[],
      targetArray: any[],
      source: any,
      type: number
    ) => {
      for (let key in source) {
        state.isHasTreeNode = false;
        findTreeItem(treeArray, targetArray, source[key], type, key);
      }
    };

    //根据详情返回的信息查找对应的树节点
    const findTreeItem = (
      treeArray: any[],
      targetArray: any[],
      source: any,
      type: number,
      sourceKey?: any
    ) => {
      //找到了，退出递归
      if (state.isHasTreeNode) {
        return false;
      }
      for (let item of treeArray) {
        if (item.id == source.id) {
          //克隆防止引用地址一致
          item = _.cloneDeep(toRaw(item));
          if (type == 1) {
            //筛选条件
            item.operator = source.operator;
            item.value = source.value.split(',');
            item.rangeType = source.rangeType;
            item.content = source.content.split(',');
          } else if (type == 2) {
            item.aggregationId = source.aggregationId;
          }
          //有索引直接赋值
          if (sourceKey) {
            targetArray[sourceKey] = item;
          } else {
            targetArray.push(item);
          }
          state.isHasTreeNode = true;
        } else {
          if (item.children) {
            findTreeItem(item.children, targetArray, source, type);
          }
        }
      }
    };

    /** 场景取数模块的接口 */
    // 获取场景列表
    const getScenesList = async () => {
      let params = {
        status: 0
      };
      const res = await API.scene.postSceneList({ ...params });
      if (res.code === 200) {
        scenesList.value = res.data;
        if (scenesList.value && scenesList.value.length) {
          if (!route.query.sceneId && !route.query.taskId) {
            handleSelect(scenesList.value[0]);
          }
          if (route.query.sceneId) {
            scenesList.value.map((item: any) => {
              if (item.id == route.query.sceneId) {
                handleSelect(item);
                return;
              }
            });
          }
        }
      }
    };

    // 获取对应场景列表下的指标/维度
    const getDimensionMetrics = async (id: number) => {
      defaultSceneId.value = id;
      const { code, data } = await API.sceneTaskManager.getSceneDetailById({
        id: id
      });
      if (code === 200) {
        processData(data);
      }
    };

    // 选择下拉的场景
    const handleSelect = (val: any) => {
      console.log('正常的下拉的场景');
      // 清空数据
      state.treeNodeData = {
        childrenTree: null,
        opType: 'AND', // 与或非
        //可选指标或维度: 数值 ,检举；日期
        treeList: [] as any[], //节点数据
        level: 0
      }; //筛选条件数据
      state.tableHeaderList = []; //表头拖拽数据
      state.maxQueryNumber = 1000;
      state.visibleSave = false;
      state.saveLoading = false;
      state.editFormData = undefined;
      state.taskHisId = 0; //任务id
      state.tableData = {
        list: [] as any[],
        pageNum: 1,
        pageSize: 10,
        total: 0
      }; //表格数据
      state.previewData = {}; //预览数据
      state.isHasTreeNode = false; //判断是否找到树节点
      state.chosenDimensionIds = []; //可选维度id
      state.chosenMetricsIds = []; //可选指标id
      state.metricsNodkey = ''; //指标树展开
      state.dimensionNodkey = ''; //维度树展开

      route.query.taskId = '';
      defaultSceneName.value = val.cnName;
      defaultSceneId.value = val.id;
      store.commit('metricsapplication/changeScenesId', val.id);
      getDimensionMetrics(val.id);
    };

    // 用于在任务详情里面获取选中的场景
    const handleSelectFromDetail = (val: any) => {
      console.log('任务详情里面获取选中的场景');
      defaultSceneName.value = val.cnName;
      defaultSceneId.value = val.id;
      getDimensionMetrics(val.id);
    };

    // 处理场景取数下的指标/维度（处理成树形结构）
    const processData = (data: any) => {
      data.dimensionList?.forEach((item: any) => {
        delete item.subjectId;
        delete item.subjectName;
        item.id = item.dimensionId;
        item.cnName = item.dimensionName;
        item.enName = item.dimensionEnName;
      });
      data.metricsList?.forEach((item: any) => {
        delete item.subjectId;
        delete item.subjectName;
        item.id = item.metricsId;
        item.cnName = item.metricsName;
        item.enName = item.metricsEnName;
      });
      data.timePeriodList?.forEach((item: any) => {
        delete item.subjectId;
        delete item.subjectName;
        item.id = item.timePeriodId;
        item.cnName = item.timePeriodName;
        item.enName = item.timePeriodEnName;
      });
      //处理指标
      let metricsTreeList: any[] = [];
      let metricsRoot = {
        id: '',
        cnName: '全部指标',
        num: data.metricsList?.length,
        children: []
      };
      getDimensionTreeData(metricsRoot, data.metricsList);
      metricsTreeList.push(metricsRoot);
      state.metricsTreeList = metricsTreeList;

      //处理维度
      let dimensionTreeList: any[] = [];
      let dimensionRoot = {
        id: '',
        cnName: '全部维度',
        num: data.dimensionList?.length,
        children: []
      };
      getDimensionTreeData(dimensionRoot, data.dimensionList);
      dimensionTreeList.push(dimensionRoot);

      //处理统计粒度
      let timeRoot = {
        id: '',
        cnName: '统计粒度',
        num: data.timePeriodList?.length,
        children: []
      };
      getDimensionTreeData(timeRoot, data.timePeriodList);
      dimensionTreeList.push(timeRoot);
      state.dimensionTreeList = dimensionTreeList;
    };

    // 场景取数下的预览数据
    const previewScenesData = async () => {
      let previewData = doPreviewData();
      if (previewData) {
        state.saveLoading = true;
        const { code, data, msg }: any =
          await API.sceneTaskManager.postPreviewData({
            ...previewData,
            sceneId: defaultSceneId.value
          });
        if (code === 200 && data) {
          state.taskHisId = data;
          getResultList();
        } else {
          ElMessage.error(msg);
          state.saveLoading = false;
        }
      }
    };

    //更新可选树结构
    watch(
      () => [state.chosenDimensionIds.length, state.chosenMetricsIds.length],
      (val: any) => {
        //判断收藏
        let isMetricsFavorite = state.command == '1' ? false : true;
        if (!isShowScenes.value) {
          getIndexTree(
            isMetricsFavorite,
            state.chosenDimensionIds,
            state.chosenMetricsIds
          );
        }
      }
    );

    //查询树形结束后在查询详情
    onMounted(async () => {
      if (route.name === 'applicationFetchScene') {
        // 来自场景取数
        isShowScenes.value = true;
        await getScenesList();
      } else {
        isShowScenes.value = false;
        await getIndexTree();
      }
      //判断是否有任务id
      if (route.query.taskId) {
        taskDetail(route.query.taskId);
      }
      store.commit('breadcrumb/setShowReturn', true); //是否显示返回
      // 返回对象及返回动作
      store.commit('breadcrumb/setBackParams', {
        name: RouteNames.ROUTE_APPLICATIONFETCH
      });
    });

    return () => {
      return (
        <>
          <PageCaontainer show-back={true}>
            <div class="fetch-data-config">
              {!isShowScenes.value ? (
                <div
                  class="left"
                  style={{
                    width: toggle.value ? '0px' : '210px'
                  }}
                >
                  <img
                    class={['shrink', toggle.value && 'shrinkRight']}
                    onClick={() => (toggle.value = !toggle.value)}
                    src={shrinkIcon.value}
                    onMouseenter={() => (shrinkIcon.value = activeShrinkLeft)}
                    onMouseout={() => (shrinkIcon.value = shrinkLeft)}
                    alt=""
                  />
                  <div
                    class="tab-menu"
                    style={{
                      overflow: toggle.value ? 'hidden' : 'initial',
                      height: toggle.value ? '0' : 'initial'
                    }}
                  >
                    <el-dropdown
                      onCommand={(command: string) => {
                        state.command = command;
                        //查询收藏指标
                        getIndexTree(state.command == '1' ? false : true);
                        //清空数据
                        state.treeNodeData = {
                          childrenTree: null,
                          opType: 'AND', // 与或非
                          //可选指标或维度: 数值 ,检举；日期
                          treeList: [] as any[], //节点数据
                          level: 0
                        }; //筛选条件数据
                        state.tableHeaderList = []; //表头拖拽数据
                        state.maxQueryNumber = 1000;
                        state.visibleSave = false;
                        state.saveLoading = false;
                        state.editFormData = undefined;
                        state.taskHisId = 0; //任务id
                        state.tableData = {
                          list: [] as any[],
                          pageNum: 1,
                          pageSize: 10,
                          total: 0
                        }; //表格数据
                        state.previewData = {}; //预览数据
                        state.isHasTreeNode = false; //判断是否找到树节点
                        state.chosenDimensionIds = []; //可选维度id
                        state.chosenMetricsIds = []; //可选指标id
                        state.metricsNodkey = ''; //指标树展开
                        state.dimensionNodkey = ''; //维度树展开
                      }}
                      v-model={state.isMetricsFavorite}
                      trigger="click"
                      v-slots={{
                        dropdown: () => (
                          <el-dropdown-menu>
                            <el-dropdown-item command="1">
                              指标市场
                            </el-dropdown-item>
                            <el-dropdown-item command="2">
                              我的收藏
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        )
                      }}
                    >
                      <div class="menu-list">
                        {state.command == '1' ? '指标市场' : '我的收藏'}
                        <el-icon>
                          <CaretBottom />
                        </el-icon>
                      </div>
                    </el-dropdown>
                  </div>
                  <div class="index-list">
                    <div class="select-index" v-drawerDrag>
                      <DragTree
                        treeTitle="可选指标"
                        onRefreshTree={refreshTree}
                        treeData={state.metricsTreeList}
                        v-model:nodeKey={state.metricsNodkey}
                      ></DragTree>
                    </div>
                    <div class="line">
                      <img id="lineId" src={dragTop} class="drag-svg"></img>
                      <ElDivider></ElDivider>
                    </div>
                    <div class="select-dimension">
                      <DragTree
                        treeTitle="可选维度"
                        onRefreshTree={refreshTree}
                        treeData={state.dimensionTreeList}
                        v-model:nodeKey={state.dimensionNodkey}
                      ></DragTree>
                    </div>
                  </div>
                </div>
              ) : (
                <div
                  class="left"
                  style={{
                    width: toggle.value ? '0px' : '210px'
                  }}
                >
                  <img
                    class={['shrink', toggle.value && 'shrinkRight']}
                    onClick={() => (toggle.value = !toggle.value)}
                    src={shrinkIcon.value}
                    onMouseenter={() => (shrinkIcon.value = activeShrinkLeft)}
                    onMouseout={() => (shrinkIcon.value = shrinkLeft)}
                    alt=""
                  />
                  <div
                    class="tab-menu"
                    style={{
                      overflow: toggle.value ? 'hidden' : 'initial',
                      height: toggle.value ? '0' : 'initial'
                    }}
                  >
                    <a-dropdown
                      onSelect={handleSelect}
                      v-slots={{
                        content: () => (
                          <>
                            {scenesList.value.map((item: any) => {
                              return (
                                <a-doption value={item}>
                                  {item.cnName}
                                </a-doption>
                              );
                            })}
                          </>
                        )
                      }}
                    >
                      <div class="menu-list" style={{ cursor: 'pointer' }}>
                        {defaultSceneName.value}
                        <el-icon>
                          <CaretBottom />
                        </el-icon>
                      </div>
                    </a-dropdown>
                  </div>
                  <div class="index-list">
                    <div
                      class="select-index"
                      v-drawerDrag
                      style={{ flex: '0 0 32%' }}
                    >
                      <DragTree
                        treeTitle="可选指标"
                        onRefreshTree={refreshTree}
                        treeData={state.metricsTreeList}
                        v-model:nodeKey={state.metricsNodkey}
                      ></DragTree>
                    </div>
                    <div class="line">
                      <img id="lineId" src={dragTop} class="drag-svg"></img>
                      <ElDivider></ElDivider>
                    </div>
                    <div class="select-dimension">
                      <DragTree
                        treeTitle="可选维度"
                        onRefreshTree={refreshTree}
                        treeData={state.dimensionTreeList}
                        v-model:nodeKey={state.dimensionNodkey}
                      ></DragTree>
                    </div>
                  </div>
                </div>
              )}

              <div class="right">
                <div class="right-top">
                  <span class="title">筛选条件</span>
                  <ElButton type="primary" onClick={openSave}>
                    保存任务
                  </ElButton>
                </div>
                <div class="dragList">
                  <ConditionTree
                    treeNodeData={state.treeNodeData}
                    onAddNode={addNode}
                    onRemoveNode={removeNode}
                  />
                </div>
                <div class="right-middle">
                  <span class="max-querynum-label">查询条数</span>
                  <el-input-number
                    v-model={state.maxQueryNumber}
                    class="max-querynum-input"
                    size="large"
                    controls-position="right"
                    placeholder="请输入最大呈现条数"
                  ></el-input-number>
                  <ElButton
                    loading={state.saveLoading}
                    class="preview-btn"
                    onClick={
                      !isShowScenes.value ? doPreview : previewScenesData
                    }
                    plain
                  >
                    数据预览
                  </ElButton>
                </div>
                <ElDivider class="mid-divider"/>
                <div class="right-top">
                  <span class="title">取数结果</span>
                  <ElButton type="primary" onClick={downloadTask}>
                    下载表格
                  </ElButton>
                </div>
                <TableHeaderDrag
                  tableHeaderList={state.tableHeaderList}
                  tableData={state.tableData}
                  chosenDimensionIds={state.chosenDimensionIds}
                  chosenMetricsIds={state.chosenMetricsIds}
                  isMetricsFavorite={state.isMetricsFavorite}
                  onRemoveItem={removeItem}
                  onUpdateItem={updateItem}
                  onFilterColomn={filterColomn}
                  onPageSizeChange={pageChange}
                  onCurrentChange={currentChange}
                ></TableHeaderDrag>
              </div>
            </div>
            {state.visibleSave && (
              <TaskSaveDrawer
                saveLoading={state.saveLoading}
                editData={state.editFormData}
                drawerVisible={state.visibleSave}
                onHandleClose={drawerClose}
                onSaveTask={saveTask}
              ></TaskSaveDrawer>
            )}
          </PageCaontainer>
        </>
      );
    };
  }
});

export default FetchDataConfig;
